package com.athuahua.webflux;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;

/**
 * @Author: huahua
 * @Date: 2024/11/16 0016
 * @Time: 15:49
 * @Description:
 */
//原生API创建的服务器
public class FluxMainApplication {
    public static void protogenesisMain(String[] args) throws IOException {
        //快速自己编写一个能处理请求的服务器
        //1.创建一个能处理http请求的处理器
        HttpHandler httpHandler = (ServerHttpRequest request, ServerHttpResponse response) -> {
//            response.bufferFactory() //buffer工厂
//            response.writeWith() //把xxx写出去
//            response.setComplete(); //响应结束
            System.out.println(Thread.currentThread() + " 请求进来了：" + request.getURI());
            //编写请求处理的业务
            //给浏览器发送Hello world

            //创建响应数据的buffer
            DataBufferFactory factory = response.bufferFactory();
            DataBuffer helloWorld = factory.wrap("hello world !".getBytes());

            //需要一个 DataBuffer的发布者
            return response.writeWith(Mono.just(helloWorld));
        };

        //2.启动一个服务器，监听8080端口，接受数据，拿到数据，交给Handler 进行请求处理
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

        //3.启动netty服务器
        HttpServer.create()
                .host("localhost")
                .port(8080)
                .handle(adapter)
                .bindNow(); //现在就启动


        System.out.println("服务器启动.监听8080端口，接受请求");

        System.in.read();
        System.out.println("服务器停止");


    }
}